package ru.jexp.rcp.supply.beans.project.dvs.sostavizdelia;

import org.eclipse.core.databinding.observable.value.AbstractObservableValue;
import org.eclipse.core.databinding.observable.value.ValueDiff;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;

public class SostavIzdeliaSelectionObservableValue extends AbstractObservableValue implements ISelectionChangedListener
{
	private Object selected;
	
	public SostavIzdeliaSelectionObservableValue(TreeViewer viewer)
	{
		viewer.addPostSelectionChangedListener(this);
	}

	@Override
	public Object getValueType()
	{
		return TreePathMerge.class;
	}

	@Override
	protected Object doGetValue()
	{
		return selected;
	}

	private Object getSelection(StructuredSelection selection)
	{
		return selection.isEmpty() ? null : selection.getFirstElement();
	}

	@Override
	public void selectionChanged(final SelectionChangedEvent event)
	{
		selected = getSelection((StructuredSelection) event.getSelection());
		fireValueChange(new ValueDiff()
		{
			@Override
			public Object getOldValue()
			{
				return null;
			}
			
			@Override
			public Object getNewValue()
			{
				return getSelection((StructuredSelection) event.getSelection());
			}
		});
	}
}